package com.javaweb.newservlelt;

import com.javaweb.common.DBUtil;
import com.javaweb.common.DispatcherTool;
import com.javaweb.common.StringTool;
import com.javaweb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * the servlet for login ：
 * There are two ways to configure servlet
 * A. by web.xml
 * B. @WebServlet (servlet 3.0)
 */
@WebServlet(name="login",
            urlPatterns = {"/login"}
)
public class LoginServlet extends HttpServlet {
    public static final String USER_COOKIE = "user" ;
    public static final String UER_ATTR = "user" ;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp) ;
    }

    /**
     * the  main processing request was defined in this method.
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 一般而言，三步处理请求
         *
         */
        System.out.println("[INFO] LoginServlet: entered.") ;
        req.setCharacterEncoding(StringTool.UTF);
        /*
        Got parameters
         */
        String name = req.getParameter("name") ;
        String pwd = req.getParameter("pwd") ;

        System.out.println("[INFO] LoginServlet: parameters: " +name
                                  + ", " +pwd) ;

        if (StringTool.isEmpty(name, pwd)) {
            System.out.println("[INFO] LoginServlet: parameter was NULL.") ;
            DispatcherTool.indirectForwardToClient(req, resp, "02/servlet/login.jsp", "参数为空！");
            return ;
        }
        User user = DBUtil.userLogin(name, pwd) ;
        if (user == null) {
            System.out.println("[INFO] LoginServlet: invalidated user.") ;
            DispatcherTool.indirectForwardToClient(req, resp, "02/servlet/login.jsp", "密码不正确！");
            return ;
        }

        /**
         * process free login
         */
        String free = req.getParameter("free") ;
        if (! StringTool.isEmpty(free)) {
            /**
             * add a user cookie for free login.
             */
            String encryptedUserInfor = StringTool.encrypt(name, pwd) ;
            Cookie cookie = new Cookie(USER_COOKIE, encryptedUserInfor) ;
            cookie.setMaxAge(2 * 60);
            resp.addCookie(cookie) ;
            System.out.println("[INFO] a cookie was added in LoginServlet") ;
        }
        //cache validated user in session
        HttpSession session = req.getSession() ;
        session.setAttribute("user", user);
        DispatcherTool.indirectForwardToClient(req, resp,
                                      "02/servlet/welcome.jsp",
                                     "登录成功！");

    }


}
